package com.rh.controller;


import com.rh.entity.EduVideo;
import com.rh.feign_service.FeignEduService;
import com.rh.service.EduVideoService;
import com.rh.exception.EducationException;
import com.rh.result.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 课程视频 前端控制器
 * @author rh
 * @since 2021-09-24
 */
@Api(tags = "小节管理")
@RestController
@RequestMapping("/eduservice/video")
public class EduVideoController {
    @Autowired
    private EduVideoService eduVideoService;
    //注入feign服务
    @Autowired
    private FeignEduService feignEduService;
    /**
     * 1.添加小节
     */
    @ApiOperation(value = "1.添加小节")
    @PostMapping("addVideo")
    public ResultVo addVideo(@RequestBody EduVideo eduVideo){
        String title = eduVideo.getTitle();
        Integer sort = eduVideo.getSort();
        String videoSourceId = eduVideo.getVideoSourceId();
        if (StringUtils.isEmpty(title)){
            return ResultVo.error().message("标题不能为空");
        }
        /*if(StringUtils.isEmpty(videoSourceId)){
            return ResultVo.error().message("视频未上传");
        }*/
        boolean save = eduVideoService.save(eduVideo);
        if(save){
            return ResultVo.ok();
        }else {
            return ResultVo.error();
        }
    }
    /**
     * 2.删除小节
     */
    @ApiOperation(value = "2.删除小节")
    @DeleteMapping("{id}")
    public ResultVo deleteVideo(@PathVariable String id){
        // 使用微服务的方法删除小节中的视频
        //先根据小节id获得视频id 然后嗲用微服务中得方法删除小节中的视频
        //根据小节id获取EduVideo对象
        EduVideo eduVideo = eduVideoService.getById(id);
        //通过EudVideo对象获得视频id
        String videoSourceId = eduVideo.getVideoSourceId();
        //调用微服务中的删除视频方法删除小节中的视频
        if (!StringUtils.isEmpty(videoSourceId)){
            ResultVo resultVo = feignEduService.removeAlyVideo(videoSourceId);
            if(resultVo.getCode()==20001){
                throw new EducationException(20001,"删除视频失败,熔断器执行...........");
            }
        }
        eduVideoService.removeById(id);
        return ResultVo.ok();
    }
    /**
     * 3.根据id查询小节信息
     */
    @ApiOperation(value = "3.根据id查询小节信息")
    @GetMapping("getVideo/{id}")
    public ResultVo getVideoInfo(@PathVariable String id){
        EduVideo eduVideo = eduVideoService.getById(id);
        return ResultVo.ok().data("video",eduVideo);
    }
    /**
     * 4.修改小节
     */
    @ApiOperation(value = "4.修改小节")
    @PostMapping("updateVideo")
    public ResultVo updateVideo(@RequestBody EduVideo eduVideo){
        boolean b = eduVideoService.updateById(eduVideo);
        if(b){
            return ResultVo.ok();
        }else {
            return ResultVo.error();
        }
    }
}

